﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography.X509Certificates;

namespace BigWoo.Apps.CertToolLib
{
    public static class Search
    {
        private static CertificateDataCollection FindBy(StoreName store, StoreLocation location)
        {
            StoreNameType storeNameType = (StoreNameType)Enum.Parse(typeof(StoreNameType), store.ToString());
            StoreLocationType storeLocationType = (StoreLocationType)Enum.Parse(typeof(StoreLocationType), location.ToString());
            CertificateDataCollection list = new CertificateDataCollection();

            X509Store certificateStore = new X509Store(store, location);

            try
            {
                certificateStore.Open(OpenFlags.ReadOnly);

                X509Certificate2Collection clientCertificates = certificateStore.Certificates;

                foreach (X509Certificate2 cert in clientCertificates)
                {
                    CertificateData data = new CertificateData();
                    data.StoreName = storeNameType;
                    data.StoreLocation = storeLocationType;
                    data.CertName = cert.SubjectName.Name;
                    data.Subject = cert.Subject;
                    data.SerialNo = cert.SerialNumber;
                    data.ThumbPrint = cert.Thumbprint;

                    list.Add(data);
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (null != certificateStore)
                {
                    try
                    {
                        certificateStore.Close();
                    }
                    catch { }
                }
            }

            return list;                 

        }

        public static CertificateDataCollection FindAllMy()
        {
            return FindBy(StoreName.My, StoreLocation.LocalMachine);
        }

        public static CertificateDataCollection FindBy(StoreNameType storeType, StoreLocationType locationType)
        {
            StoreName store = (StoreName) Enum.Parse(typeof(StoreName), storeType.ToString());
            StoreLocation location = (StoreLocation) Enum.Parse(typeof(StoreLocation), locationType.ToString());

            return FindBy(store, location);
        }

    }
}
